package com.ruoyi.leave.instener;

import com.alibaba.excel.util.ListUtils;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.leave.util.WorkFlowConstants;
import com.ruoyi.manage.domain.BtFlowHistory;
import com.ruoyi.manage.domain.SwWaterAdjustLog;
import com.ruoyi.manage.domain.SwWaterMonthReport;
import com.ruoyi.manage.domain.SwWaterPlan;
import com.ruoyi.manage.service.IBtFlowHistoryService;
import com.ruoyi.manage.service.ISwWaterAdjustLogService;
import com.ruoyi.manage.service.ISwWaterMonthReportService;
import com.ruoyi.manage.service.ISwWaterPlanService;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.delegate.event.ActivitiEvent;
import org.activiti.engine.delegate.event.ActivitiEventListener;
import org.activiti.engine.delegate.event.impl.ActivitiEntityEventImpl;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.impl.persistence.entity.ExecutionEntityImpl;
import org.activiti.engine.impl.persistence.entity.TaskEntityImpl;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Slf4j
public class ActivitiTaskEventListener implements ActivitiEventListener {
    private HistoryService historyService;
    private TaskService taskService;
    private RuntimeService runtimeService;


    private IBtFlowHistoryService btFlowHistoryService;

    private ISwWaterPlanService waterPlanService;

    private ISwWaterMonthReportService swWaterMonthReportService;

    private ISwWaterAdjustLogService swWaterAdjustLogService;


    public ActivitiTaskEventListener(HistoryService historyService, TaskService taskService, RuntimeService runtimeService) {
        this.historyService = historyService;
        this.taskService = taskService;
        this.runtimeService = runtimeService;
        waterPlanService = SpringUtils.getBean("swWaterPlanServiceImpl");
        btFlowHistoryService = SpringUtils.getBean("btFlowHistoryServiceImpl");
        swWaterMonthReportService = SpringUtils.getBean("swWaterMonthReportServiceImpl");
        swWaterAdjustLogService = SpringUtils.getBean("swWaterAdjustLogServiceImpl");
    }

    @Override
    public void onEvent(ActivitiEvent activitiEvent) {
        switch (activitiEvent.getType()) {
            // 任务执行后
            case TASK_COMPLETED:
                log.info("TASK_COMPLETED,{}", activitiEvent.getProcessInstanceId());
                break;
            case TASK_CREATED:
                log.info("TASK_CREATED,{}", activitiEvent.getProcessInstanceId());
                if (activitiEvent instanceof ActivitiEntityEventImpl) {
                    ActivitiEntityEventImpl eventImpl = (ActivitiEntityEventImpl) activitiEvent;
                    if (eventImpl.getEntity() instanceof TaskEntityImpl) {
                        TaskEntityImpl taskEntityImpl = (TaskEntityImpl) eventImpl.getEntity();
                        if ("firstUserTask".equalsIgnoreCase(taskEntityImpl.getTaskDefinitionKey())) {
                            String processInstanceId = activitiEvent.getProcessInstanceId();

                            List<HistoricActivityInstance> historicActivityInstanceList = historyService.createHistoricActivityInstanceQuery().
                                    processInstanceId((processInstanceId)).list();
                            if (historicActivityInstanceList.size() > 2) {
                                //驳回到填报时
                                log.info("驳回到用户填报了");
                                Map<String, Object> variables = taskEntityImpl.getVariables();
                                String planId = variables.get("planId").toString();
                                String key = variables.get("key").toString();
                                if (ListUtils.newArrayList(WorkFlowConstants.WORK_FLOW_WATER_MONTH_BUSINESS_KEY
                                        , WorkFlowConstants.WORK_FLOW_WATER2_MONTH_BUSINESS_KEY).contains(key)) {
                                    //月底
                                    SwWaterMonthReport swWaterMonthReport = swWaterMonthReportService.selectSwWaterMonthReportById(Long.valueOf(planId));
                                    if (null != swWaterMonthReport) {
                                        swWaterMonthReport.setStatus("3");
                                        swWaterMonthReportService.updateSwWaterMonthReport(swWaterMonthReport);
                                    }
                                } else if (ListUtils.newArrayList(WorkFlowConstants.WORK_FLOW_WATER_ADJUST_BUSINESS_KEY
                                        , WorkFlowConstants.WORK_FLOW_WATER2_ADJUST_BUSINESS_KEY).contains(key)) {
                                    // 调整
                                    SwWaterAdjustLog swWaterAdjustLog = swWaterAdjustLogService.selectSwWaterAdjustLogById(Long.valueOf(planId));
                                    if(null != swWaterAdjustLog) {
                                        swWaterAdjustLog.setStatus("3");
                                        swWaterAdjustLogService.updateSwWaterAdjustLogDto(swWaterAdjustLog);
                                    }
                                } else {

                                    //年度
                                    SwWaterPlan swWaterPlan = waterPlanService.selectSwWaterPlanById(Long.valueOf(planId));
                                    if (null != swWaterPlan) {
                                        swWaterPlan.setStatus("3");
                                        waterPlanService.updateSwWaterPlanDto(swWaterPlan);
                                    }
                                }


                            }

                        }
                    }
                }
                break;
            case PROCESS_COMPLETED:
                log.info("PROCESS_COMPLETED,{}", activitiEvent.getProcessInstanceId());
                // 流程结束时
                log.info("流程结束了");
                if (activitiEvent instanceof ActivitiEntityEventImpl) {
                    ActivitiEntityEventImpl eventImpl = (ActivitiEntityEventImpl) activitiEvent;
                    if (eventImpl.getEntity() instanceof ExecutionEntityImpl) {
                        ExecutionEntityImpl executionEntity = (ExecutionEntityImpl) eventImpl.getEntity();
                        Map<String, Object> variables = executionEntity.getVariables();
                        // 修改计划审核状态
                        String planId = variables.get("planId").toString();
                        String key = variables.get("key").toString();
                        if (ListUtils.newArrayList(WorkFlowConstants.WORK_FLOW_WATER_MONTH_BUSINESS_KEY
                                , WorkFlowConstants.WORK_FLOW_WATER2_MONTH_BUSINESS_KEY).contains(key)) {
                            //月度
                            SwWaterMonthReport swWaterMonthReport = swWaterMonthReportService.selectSwWaterMonthReportById(Long.valueOf(planId));
                            if (null != swWaterMonthReport) {
                                swWaterMonthReport.setStatus("2");
                                swWaterMonthReportService.updateSwWaterMonthReport4Final(swWaterMonthReport);
                            }
                        } else if (ListUtils.newArrayList(WorkFlowConstants.WORK_FLOW_WATER_ADJUST_BUSINESS_KEY
                                , WorkFlowConstants.WORK_FLOW_WATER2_ADJUST_BUSINESS_KEY).contains(key)) {
                            // 调整
                            Long adjustId = Long.valueOf(planId);
                            SwWaterAdjustLog swWaterAdjustLog = new SwWaterAdjustLog();
                            swWaterAdjustLog.setId(adjustId);
                            swWaterAdjustLog.setStatus("2");
                            swWaterAdjustLogService.updateSwWaterAdjustLogDto(swWaterAdjustLog);
                            // 数据同步
                            swWaterAdjustLogService.adjustingDataSynchronization(adjustId);
                        } else {
                            //年度
                            SwWaterPlan swWaterPlan = waterPlanService.selectSwWaterPlanById(Long.valueOf(planId));
                            if (null != swWaterPlan) {
                                swWaterPlan.setStatus("2");
                                waterPlanService.updateSwWaterPlanDto(swWaterPlan);

                                // 添加审核日志信息
                                BtFlowHistory btFlowHistory = new BtFlowHistory();
                                btFlowHistory.setcDate(new Date());
                                SysUser user = SecurityUtils.getLoginUser().getUser();
                                btFlowHistory.setUserId(user.getUserId());
                                btFlowHistory.setUserName(user.getNickName());
                                btFlowHistory.setReason("通过");
                                btFlowHistory.setServiceId(Long.valueOf(planId));
                                btFlowHistoryService.insertBtFlowHistory(btFlowHistory);
                            } else {
                                log.info("当前流程Id找不到记录: " + Long.valueOf(planId));
                            }
                        }

                    }
                }
                break;
            default:
        }
    }

    @Override
    public boolean isFailOnException() {
        return false;
    }

}
